const express = require('express')
const blogTable = require('../../db/blog/blogTable')
const userTable = require('../../db/user/userTable')
const userDetailTable = require('../../db/user/userDetailTable')
const GlobalUtils = require('../../tools/GlobalUtils')
const { ObjectId } = require('bson')

// 用于处理用户详情操作的服务 例如点赞、关注、拉黑等业务
const userDetailApp = express()

// 查询用户信息
userDetailApp.get('/users', async (req, res) => {
  const { limit, offset, searchKey } = req.query

  const filter = {
    __v: false,
    createTime: false,
    approved: false,
    password: false,
    key: false,
    token: false
  }

  // 模糊查询
  const users = await userTable.find({ userName: { $regex: searchKey } })

  // 总数量
  const total = users.length

  if (total === 0) {
    return res.send({
      status: 404,
      message: '用户不存在！'
    })
  }

  // 分页查询
  const userPage = await userTable.find(
    { userName: { $regex: searchKey, $options: '$i' } },
    { ...filter },
    {
      limit: Number(limit),
      skip: Number(offset)
    }
  )

  res.send({
    status: 200,
    message: 'OK',
    data: {
      total,
      userPage
    }
  })
})

// 鉴权的时候就把用户信息缓存起来 后续就不必再查数据库了
let userData = {}

// 操作鉴权
userDetailApp.all('/*', async (req, res, next) => {
  let permission = await userTable.find({ token: req.headers.authorization })
  if (permission.length) {
    userData = permission[0]
    next()
  } else {
    res.send({
      status: 403,
      message: '无操作权限'
    })
  }
})

// 点赞
userDetailApp.post('/likes', async (req, res) => {
  // 博客详情表 点赞数 +1
  await blogTable.updateOne(
    { blogId: req.body.blogId },
    { $inc: { likes: 1 } }
  )

  // 用户详情表 点赞数组 更新文章 id 
  await userDetailTable.updateOne(
    { key: userData.key },
    { $push: { likes: req.body.blogId } }
  )

  res.send({
    status: 200,
    message: '点赞成功！'
  })
})

// 取消点赞
userDetailApp.delete('/likes/:blogId', async (req, res) => {
  // 博客详情表 点赞数 -1
  await blogTable.updateOne(
    { blogId: Number(req.params.blogId) },
    { $inc: { likes: -1 } }
  )

  // 用户详情表 点赞数组 移除文章 id 
  await userDetailTable.updateOne(
    { key: userData.key },
    { $pull: { likes: Number(req.params.blogId) } }
  )

  res.send({
    status: 200,
    message: '已取消点赞！'
  })
})

// 关注
userDetailApp.post('/attention', async (req, res) => {

  // 找到 被关注的用户
  let author = await userTable.findOne(
    { _id: req.body.userId }
  )

  if (!author) return res.send({ status: 404, message: '用户不存在！' })

  // 用户详情表 关注数组 更新关注用户
  await userDetailTable.updateOne(
    { key: userData.key },
    { $push: { attentions: req.body.userId } }
  )

  // 把当前用户加入到对方的粉丝团里
  await userDetailTable.updateOne(
    { key: author.key },
    { $push: { fans: userData._id } }
  )

  res.send({
    status: 200,
    message: '关注成功！'
  })
})

// 取关
userDetailApp.delete('/attention/:userId', async (req, res) => {

  // 用户详情表 关注数组 移除该用户 
  await userDetailTable.updateOne(
    { key: userData.key },
    { $pull: { attentions: req.params.userId } }
  )

  // 找到 被关注的用户的 
  let author = await userTable.findOne(
    { _id: req.params.userId }
  )

  if (author) {
    // 把当前用户移出对方的粉丝团
    await userDetailTable.updateOne(
      { key: author.key },
      { $pull: { fans: userData._id } }
    )
  }

  res.send({
    status: 200,
    message: '取关成功！'
  })
})

// 移除粉丝
userDetailApp.delete('/fans/:userId', async (req, res) => {

  // 用户详情表 我的粉丝数组 移除该用户 
  await userDetailTable.updateOne(
    { key: userData.key },
    { $pull: { fans: ObjectId(req.params.userId) } }
  )

  // 找到 被移除粉丝的用户 
  let author = await userTable.findOne(
    { _id: req.params.userId }
  )

  if (author) {
    // 把我移出对方的关注列表
    await userDetailTable.updateOne(
      { key: author.key },
      { $pull: { attentions: String(userData._id) } }
    )
  }

  res.send({
    status: 200,
    message: '移出成功！'
  })
})

// 加入黑名单
userDetailApp.post('/blackList', async (req, res) => {

  const author = await userTable.findOne({ _id: req.body.userId })

  if (!author) return res.send({ status: 404, message: '用户不存在！' })

  // 用户详情表 黑名单 +1
  await userDetailTable.updateOne(
    { key: userData.key },
    { $push: { blackList: req.body.userId } }
  )

  res.send({
    status: 200,
    message: '拉黑成功！'
  })
})

// 从黑名单移除
userDetailApp.delete('/blackList/:userId', async (req, res) => {
  // 用户详情表 黑名单 -1
  await userDetailTable.updateOne(
    { key: userData.key },
    { $pull: { blackList: req.params.userId } }
  )

  res.send({
    status: 200,
    message: '移出成功！'
  })
})

// 获取我的评论信息
userDetailApp.get('/myComment', async (req, res) => {
  const { limit, offset } = req.query

  // 查找评论数据
  const userDetails = await userDetailTable.findOne({ key: userData.key })
  const comments = userDetails.comments
  const total = comments.length
  // 手动截取 做分页处理
  const commentList = comments.reverse().slice(Number(offset), Number(limit) + Number(offset))
  const blogIds = []
  // 提取文章 id
  commentList.forEach(item => blogIds.push(item.blogId))
  const blogs = await blogTable.find(
    { blogId: { $in: blogIds } },
    { _id: false, author_id: true, title: true, blogId: true }
  )
  // 更新标题信息
  commentList.forEach(item => {
    let blog = blogs.find(blog => blog.blogId === item.blogId)
    if (blog) {
      item.title = blog.title
      item.author_id = blog.author_id
    }
  })
  // 提取文章作者 id
  const authorsId = []
  blogs.forEach(author => authorsId.push(author.author_id))
  const authorsInfo = await userTable.find(
    { _id: { $in: authorsId } },
    { userName: true, avatar: true }
  )
  // 更新作者信息
  commentList.forEach(item => {
    let author = authorsInfo.find(user => String(user._id) === String(item.author_id))
    if (author) {
      item.authorName = author.userName
      item.authorAvatar = author.avatar
    } else {
      item.authorName = '该账号已注销'
      item.authorAvatar = ''
    }
  })

  res.send({
    status: 200,
    message: 'OK',
    data: {
      userData: {
        name: userData.userName,
        avatar: userData.avatar
      },
      total,
      commentList
    }
  })
})

// 获取我的关注列表
userDetailApp.get('/myAttentions', async (req, res) => {
  const { limit, offset, searchKey } = req.query

  const userDetails = await userDetailTable.findOne({ key: userData.key })
  const attentions = userDetails.attentions
  const total = attentions.length
  let attentionList = []
  const filter = {
    __v: false,
    createTime: false,
    approved: false,
    password: false,
    key: false,
    token: false
  }
  // 模糊查询
  if (searchKey) {
    attentionList = await userTable.find(
      {
        _id: { $in: attentions },
        userName: { $regex: searchKey }
      },
      { ...filter }
    )

  } else {

    const attentionPage = attentions.slice(Number(offset), Number(limit) + Number(offset))
    attentionList = await userTable.find(
      { _id: { $in: attentionPage } },
      { ...filter }
    )
  }

  res.send({
    status: 200,
    message: 'OK',
    data: {
      total,
      attentionList
    }
  })
})

// 获取我的粉丝列表
userDetailApp.get('/myFans', async (req, res) => {
  const { limit, offset, searchKey } = req.query

  const userDetails = await userDetailTable.findOne({ key: userData.key })
  const fans = userDetails.fans
  const total = fans.length
  let fansList = []
  const filter = {
    __v: false,
    createTime: false,
    approved: false,
    password: false,
    key: false,
    token: false
  }
  // 如果有搜索关键字 就直接查有没有这个人
  if (searchKey) {
    fansList = await userTable.find(
      {
        _id: { $in: fans },
        userName: { $regex: searchKey }
      },
      { ...filter }
    )

  } else {

    const fansPage = fans.slice(Number(offset), Number(limit) + Number(offset))
    fansList = await userTable.find(
      { _id: { $in: fansPage } },
      { ...filter }
    )
  }

  res.send({
    status: 200,
    message: 'OK',
    data: {
      total,
      fansList
    }
  })
})

// 获取我的黑名单列表
userDetailApp.get('/myBlackList', async (req, res) => {
  const { limit, offset, searchKey } = req.query

  const userDetails = await userDetailTable.findOne({ key: userData.key })
  const blacks = userDetails.blackList
  const total = blacks.length
  let blackList = []
  const filter = {
    __v: false,
    createTime: false,
    approved: false,
    password: false,
    key: false,
    token: false
  }
  // 如果有搜索关键字 就直接查有没有这个人
  if (searchKey) {
    blackList = await userTable.find(
      {
        _id: { $in: blacks },
        userName: { $regex: searchKey }
      },
      { ...filter }
    )

  } else {

    const blackPage = blacks.slice(Number(offset), Number(limit) + Number(offset))
    blackList = await userTable.find(
      { _id: { $in: blackPage } },
      { ...filter }
    )
  }

  res.send({
    status: 200,
    message: 'OK',
    data: {
      total,
      blackList
    }
  })
})

// 更新用户信息
userDetailApp.post('/settings', async (req, res) => {
  const userInfo = req.body

  // 如果更新密码 则进行加密处理
  if (userInfo.password) {
    userInfo.password = GlobalUtils.enCryptData(userInfo.password, userData.key, 'sha256')
  }

  // 用户名是否存在
  if (userInfo.userName) {
    const user = await userTable.findOne({ userName: userInfo.userName })
    if (user) {
      return res.send({
        status: 500,
        message: '用户名已存在！'
      })
    }
  }

  // 更新数据库
  const rs = await userTable.updateOne(
    { userName: userData.userName },
    { $set: { ...userInfo } }
  )

  if (rs.modifiedCount > 0) {
    res.send({
      status: 200,
      message: '修改成功！'
    })
  } else {
    res.send({
      status: 500,
      message: '修改失败！'
    })
  }
})

module.exports = userDetailApp